package com.module.itemeditor;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.phprpc.util.PHPSerializer;
import org.xsocket.connection.INonBlockingConnection;

import com.command.Group;
import com.connect.agreement.Packet;
import com.game.manager.ErrorManager;
import com.module.chat.ChatMessage;

public class EditorManager {
	public static final byte GetItemList = 1;
	public static final byte GetItemById = 2;
	public static final byte UpdateItem = 3;
	public static final byte CreateItem = 4;
	
	public static final List<CfgItem> allCfgItems = new ArrayList<CfgItem>();
	
	public static boolean is_setup = false;
	
	public static void setup(){
		List<CfgItem> list = CfgItem.getAllCfgItem();
		for(CfgItem item : list){
			allCfgItems.add(item);
		}
		is_setup = true;
	}
	
	public static void update(INonBlockingConnection nbc,Packet packet){
		if(packet == null)
			return;
		Packet retpacket = new Packet();
		byte[] bytes;
		ByteBuffer buffer;
		CfgItem item;
		try {
			switch(packet.getCmd()){
			case GetItemList:
				List<CfgItem> list = CfgItem.getAllCfgItem();
				bytes = new PHPSerializer().serialize(list);
				retpacket.setBuffer(Group.Editor, GetItemList, bytes,false);
				nbc.write(retpacket.byteBuffer());
				nbc.flush();
				break;
			case GetItemById:
				item = CfgItem.getCfgItem((Integer)new PHPSerializer().unserialize(packet.getContent()));
				bytes = new PHPSerializer().serialize(item);
				retpacket.setBuffer(Group.Editor, GetItemById, bytes,false);
				nbc.write(retpacket.byteBuffer());
				break;
			case UpdateItem:
				item = (CfgItem)new PHPSerializer().unserialize(packet.getContent());
				CfgItem.createCfgItem(item.id, item.attrs);
				break;
			case CreateItem:
				item = (CfgItem)new PHPSerializer().unserialize(packet.getContent());
				CfgItem.createCfgItem(item.id, item.attrs);
				break;
			}			
		} catch (Exception e) {
			ErrorManager.sendError(nbc, ErrorManager.EditorError);
		}
	}
}
